/*
 * hmc5883l.cpp
 *
 *  Created on: Jan 11, 2014
 *      Author: bohni
 */


#include "hmc5883l.h"

struct magnet_values magnet = { 0, 0, 0};
int16_t compass = 0;

void hmc5883l_init() {

	soft_i2c_master_init();

	uint8_t conf_tmp;

	_delay_ms(10);

	conf_tmp = eeprom_read_byte((uint8_t*) COMPASS_CONFIG_A_EEPROM_ADDRESS);
	hmc5883l_write_reg ( CONFIG_REG_A, conf_tmp);

	conf_tmp = eeprom_read_byte((uint8_t*) COMPASS_CONFIG_B_EEPROM_ADDRESS);
	hmc5883l_write_reg ( CONFIG_REG_B, conf_tmp);

	conf_tmp = eeprom_read_byte((uint8_t*) COMPASS_MODE_EEPROM_ADRESS);
	hmc5883l_write_reg ( MODE_REG, conf_tmp);

	_delay_ms(10);
}

void hmc5883l_read_values() {
	uint8_t tmp;

	soft_i2c_start(HMC5883L_WRITE_ADR);
	soft_i2c_send_data(DATA_OUT_X_MSB);

	soft_i2c_start(HMC5883L_READ_ADR);

	tmp = soft_i2c_recieve_data_ack();
	magnet.out_x = (tmp << 8);
	tmp = soft_i2c_recieve_data_ack();
	magnet.out_x |= tmp ;

	tmp = soft_i2c_recieve_data_ack();
	magnet.out_z = (tmp << 8);
	tmp = soft_i2c_recieve_data_ack();
	magnet.out_z |= tmp ;

	tmp = soft_i2c_recieve_data_ack();
	magnet.out_y = (tmp << 8);
	tmp = soft_i2c_recieve_data_nack();
	magnet.out_y |= tmp ;

	soft_i2c_stop();

}



void compute_north() {

}

void hmc5883l_self_test() {
	}

void hmc5883l_temp_compensation() {

}

void hmc5883l_write_reg ( uint8_t adr, uint8_t data) {

	soft_i2c_start(HMC5883L_WRITE_ADR);
	soft_i2c_send_data(adr);
	soft_i2c_send_data(data);
	soft_i2c_stop();

}

uint8_t hmc5883l_read_reg ( uint8_t adr) {
	uint8_t tmp;

	soft_i2c_start(HMC5883L_WRITE_ADR);
	soft_i2c_send_data(adr);
	soft_i2c_repstart(HMC5883L_READ_ADR);
	tmp = soft_i2c_recieve_data_nack();
	soft_i2c_stop();

	return tmp;
}
